package com.zzjcy.common.core.init;

import com.zzjcy.common.util.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by zhangzhi on 2017/7/12.
 */
public class CommonPropertyLoader extends PropertyPlaceholderConfigurer {
	private static Logger logger = Logger.getLogger(CommonPropertyLoader.class);

	private static final String LOG4J_PREFIX = "log4j.properties";
	private static Map<String,String> ctxPropertiesMap;
	private List<String> configs;
	private Properties[] props;

	public void init() throws Exception {
		if(StringUtils.isEmpty(System.getProperty("server.root"))){
			throw new RuntimeException("please set your project server.root path");
		}
		String serverRoot = Transformer.toLocalFilePathWithSeperatorEnd(System.getProperty("server.root"));
		logger.info("************* server.root =" + serverRoot);

		int len = this.configs.size();
		props = new Properties[len + 1];
		for (int i = 0; i < len; i++) {
			if(StringUtils.isNotBlank(configs.get(i))&& configs.get(i).contains(LOG4J_PREFIX)){
				//读取log4j配置
				String log4jPath = Transformer.toLocalFilePathWithSeperatorEnd(serverRoot + configs.get(i));
				if(!new File(log4jPath).exists()){
					throw new RuntimeException("please set your log4j relative path");
				}
				logger.info("************* log4j setting load success *************");
				PropertyConfigurator.configure(log4jPath);
			}else{
				props[i] = getProperties(new File(serverRoot + configs.get(i)));
				if(props[i] == null){
					logger.info("configs.get(i) ==" + configs.get(i) + "获取的配置信息为null");
				}
				logger.info("************* " + serverRoot + configs.get(i)  + "load success *************");
			}
		}

		processStaticMap();
		this.setPropertiesArray(props);
	}

	private Properties getProperties(File file) throws IOException {
		Properties properties =  null;
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			properties = new Properties();
			properties.load(is);
		}catch (IOException e){
			logger.error(e.getMessage());
			e.printStackTrace();
		}finally {
			if (is != null) {
				is.close();
			}
		}
		return properties;
	}

	/**
	 * 动态加载properties进内存，供业务代码使用
	 */
	public void processStaticMap()  {
		if(ctxPropertiesMap != null){
			ctxPropertiesMap.clear();
		}else{
			ctxPropertiesMap = new HashMap();
		}
		for(Properties pro : props){
			if(pro == null){
				continue;
			}
			for(Object key : pro.keySet()){
				String keyStr = key.toString();
				String value = pro.getProperty(keyStr);
				ctxPropertiesMap.put(keyStr, value);
			}
		}
	}

	public static String getProperty(String name) {
		if(ctxPropertiesMap == null){
			ctxPropertiesMap = new HashMap<>();
		}
		return ctxPropertiesMap.get(name);
	}

	public void setConfigs(List<String> configs) {
		this.configs = configs;
	}
}
